import { ComponentClass } from 'react'
import Taro, { Component, Config } from '@tarojs/taro'
import { View, Text, Input, Image } from '@tarojs/components'
import phoneLoginImg from '../../static/images/phone_login@2x.png'
import { fetch } from '../../utils/fetch'
import { inject, observer } from '@tarojs/mobx'

import './index.less'

type PageOwnProps = {
  tokenStore: {
    setToken: Function
  }
}

type PageState = {}

type IProps = PageOwnProps
interface Index {
  props: IProps
}

@inject('tokenStore')
@observer
class Index extends Component {
  config: Config = {
    navigationBarTitleText: ''
  }

  timer: any = null

  state = {
    phone: '17704051019',
    vcode: '',
    count: 10, // 倒计时总数
    isCountDown: false, // 是否正在倒计时
    tips: '获取验证码' // 提示文字
  }

  changeValue = e => {
    this.setState({
      [e.target.dataset.name]: e.target.value
    })
  }

  // 获取验证码
  getVcode = async () => {
    const { phone } = this.state

    if (phone.trim().length === 0) {
      Taro.showToast({
        title: '手机号不能为空',
        icon: 'none',
        duration: 1000
      })
      return
    }
    // 正则校验
    var reg = /^1[3456789][0-9]{9}$/
    if (!reg.test(phone)) {
      Taro.showToast({
        title: '手机号不合法',
        icon: 'none',
        duration: 1000
      })
      return
    }

    let { count, isCountDown } = this.state
    // 正在倒计时
    if (isCountDown) return

    this.setState({
      isCountDown: true,
      tips: `${this.state.count}`
    })

    this.timer = setInterval(() => {
      if (count <= 1) {
        this.setState({
          isCountDown: false,
          count: 10,
          tips: '获取验证码'
        })
        // 清除定时器
        clearInterval(this.timer)
        return
      }
      count--
      this.setState({
        tips: `${count}`
      })
    }, 1000)
    const result: any = await fetch({
      url: 'user/vcode',
      isNeedAuth: false,
      data: {
        phone
      }
    })
    if (result.data.status === 0) {
      Taro.showToast({
        title: `${result.data.vcode}`,
        icon: 'none',
        duration: 1000
      })
    }
  }

  // 手机号登录
  phoneLogin = async () => {
    const result: any = await fetch({
      method: 'POST',
      url: 'user/login',
      tips: '登录中...',
      isNeedAuth: false,
      data: {
        phone: this.state.phone,
        vcode: this.state.vcode
      }
    })

    if (result.data.status === 0) {
      // 保存token到本地及store中
      Taro.setStorageSync('my_token', result.data.token)
      this.props.tokenStore.setToken(result.data.token)
      // 提示
      Taro.showToast({
        title: result.data.message,
        icon: 'success',
        duration: 500
      })
      setTimeout(() => {
        // 跳转到首页
        Taro.reLaunch({
          url: '/pages/home/index'
        })
      }, 500)
    } else {
      Taro.showToast({
        title: result.data.message,
        icon: 'none',
        duration: 1000
      })
    }
  }

  render() {
    const { isCountDown, tips, phone, vcode } = this.state
    return (
      <View className="phone-login-container">
        <View className="phone-validate">
          <Text>手机号验证</Text>
        </View>
        <View className="subtitle">
          <Text>用于即使获取课程最新信息</Text>
        </View>
        <View className="content">
          <Input
            value={phone}
            data-name="phone"
            onInput={this.changeValue}
            className="phone"
            placeholder="请输入您的手机号"
            type="number"
          />
          <View
            onClick={this.getVcode}
            className="get_vcode"
            style={{ color: isCountDown ? '#ccc' : 'black' }}
          >
            {tips}
          </View>
          <Input
            value={vcode}
            data-name="vcode"
            onInput={this.changeValue}
            className="vcode"
            placeholder="请输入验证码"
            type="number"
          />
        </View>
        <View className="phone-login">
          <Image
            className="img"
            onClick={this.phoneLogin}
            src={phoneLoginImg}
          />
        </View>
      </View>
    )
  }
  // 页面关闭时，销毁定时器
  componentWillUnmount() {
    clearInterval(this.timer)
  }
}

export default Index as ComponentClass<PageOwnProps, PageState>
